<?php

	/**
	 * @package Yomm
	 * @author bsuter
	 *
	 */
	Abstract Class Yomm_Module_Login Extends Yomm_Controller
	{
		public $LoginSuccessUrl = null;
		
		public $LoginFailUrl = null;
		
		public $LogoutUrl = null;
		
		protected $login_message = null;
		
		public function post_verify()
		{
			if($this->verify())
			{
				Header("Location: " . SiteConfig::Domain . $this->LoginSuccessUrl);
			} else {
				Header("Location: " . SiteConfig::Domain . $this->LoginFailUrl . '&message=' . $this->login_message);
			}
		}
		
		/**
		 * @param $this->post->mail	[str]
		 * @param $this->post->pass [str]
		 * @param $this->post->secure [bool]
		 */
		public function verify()
		{
			// there is already a login active
			if(isset($this->session->user))
			{
				$this->login_message = $this->local->login_already_in();
				return false;
			}
			
			// seucure is false, so we have to md5 the password after it's send by post
			if(isset($this->post->secure))
			{
				$this->post->pass = md5($this->post->pass);
			}
			
			$obj = $this->db->select("admin_user", "*", "WHERE mail='{$this->post->mail}'", false);
			
			if(count($obj) > 1 || count($obj) == 0)
			{
				$this->login_message = $this->local->login_wrong_user($this->post->mail);
				return false;
			}
			
			if($obj->mail != $this->post->mail || $obj->pass != $this->post->pass)
			{
				$this->login_message = $this->local->login_wrong_pass();
				return false;
			}
			
			// update the login time
			$handler = $this->db->handler("admin_user", array(
				"date" => mktime()
			), "WHERE id='{$obj->id}'");
			
			$_SESSION['user'] = $obj;
			
			return true;
		}
		
		Public Function Logout ()
		{
			unset($_SESSION['user']);
			
			$_SESSION = array();
			
			session_destroy();
			
			$url = isset($this->LogoutUrl) ? SiteConfig::Domain . $this->LogoutUrl : SiteConfig::Domain;
			
			header("location: " . $url);
		}
		
	}